<template>
  <el-config-provider :locale="zhCn">
    <div class="customer-management">
      <!-- 筛选条件区域 -->
      <filter-form
        labelWidth="100px"
        v-model="filterForm"
        :form-items="formItems"
        @search="handleSearch"
        @reset="resetFilter"
        @update:modelValue="handleFilterChange"
      />

      <!-- 操作按钮区域 -->
      <div class="operation-section">
        <el-button type="primary" @click="handleAdd">新增客户</el-button>
      </div>

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table :data="tableData" border style="width: 100%" v-loading="loading" class="custom-table">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="客户信息" min-width="200">
            <template #default="{ row }">
              <div @click="handleDetail(row)" class="customer-info-clickable" style="cursor: pointer">
                <ai-wechat-info :avatar-url="row.avatarUrl" :user-name="row.userName" />
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="type" label="类型" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.type === '1' ? 'success' : 'info'" size="small">
                {{ row.type == '1' ? '好友' : '非好友' }}
              </el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="remark" label="微信备注" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.type == '1'">{{ row.remark || '-' }}</span>
              <span v-else class="no-remark">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="userAge" label="年龄" width="80" align="center">
            <template #default="{ row }">
              <span>{{ row.userAge && row.userAge > 0 ? row.userAge + '岁' : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userPhone" label="电话" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.userPhone || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userEmail" label="邮箱" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.userEmail || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userArea" label="地区" min-width="180" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ formatAreaDisplay(row.userArea, row) || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="labels" label="标签" min-width="250" show-overflow-tooltip>
            <template #default="{ row }">
              <div v-if="row.labels && row.labels.length > 0" class="tag-list">
                <el-tag v-for="label in row.labels" :key="label.id" class="tag-item" size="small">{{ label.label_name }}</el-tag>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="purchaseRecordCnt" label="购买记录" width="100" align="center">
            <template #default="{ row }">
              <span>{{ row.purchaseRecordCnt || 0 }}条</span>
            </template>
          </el-table-column>
          <el-table-column prop="medicationReminderCnt" label="用药提醒" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.medicationReminderCnt == '是' ? 'success' : 'info'" size="small">
                {{ row.medicationReminderCnt == '是' ? '已配置' : '未配置' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="industry" label="所属行业" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.industry || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userCustomerSource" label="客户来源" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.userCustomerSource || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="endMessageTime" label="最后联系时间" min-width="160" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.endMessageTime || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="添加时间" min-width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="240" fixed="right" align="center">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              <el-button v-if="row.type == 1" type="info" link @click="handleArchive(row)">档案</el-button>

              <el-popover width="170" placement="bottom-end" trigger="hover">
                <template #reference>
                  <el-button type="info" link>更多</el-button>
                </template>
                <div class="more-actions">
                  <!-- <el-button type="primary" link @click="handleDetail(row)" class="more-action-btn">详情</el-button> -->
                  <el-button type="success" link @click="handlePurchaseRecord(row)" class="more-action-btn">购买记录</el-button>
                  <el-button v-if="row.type == 1" type="warning" link @click="handleMedicationReminder(row)" class="more-action-btn">用药提醒</el-button>
                </div>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 档案对话框 -->
      <el-dialog v-model="archiveDialogVisible" title="客户档案" width="1000px" destroy-on-close class="archive-dialog">
        <div class="archive-content">
          <el-tabs v-model="activeArchiveTab" class="archive-tabs">
            <!-- 动态选项卡 -->
            <el-tab-pane label="动态" name="dynamics">
              <div class="dynamics-container">
                <div class="dynamics-content">
                  <div class="section-title">
                    客户动态
                    <div class="activity-actions">
                      <el-button type="success" size="small" @click="showAddActivityDialog" style="margin-left: 10px">新增动态</el-button>
                      <el-button
                        type="primary"
                        size="small"
                        @click="refreshCustomerActivities"
                        :loading="refreshingActivities"
                        :disabled="refreshCountdown > 0"
                        style="margin-left: 8px"
                        icon="Refresh"
                      >
                        <span v-if="refreshCountdown > 0" style="margin-left: 4px">{{ refreshCountdown }}s</span>
                      </el-button>
                    </div>
                  </div>

                  <div class="timeline-container">
                    <el-timeline v-if="customerActivities.length > 0">
                      <el-timeline-item
                        v-for="(activity, index) in customerActivities"
                        :key="index"
                        :timestamp="activity.time"
                        :type="activity.type"
                        :color="activity.color"
                        :data-type="activity.type"
                      >
                        <div class="timeline-content">
                          <div class="timeline-title">{{ activity.title }}</div>
                          <div class="timeline-desc">{{ activity.description }}</div>
                        </div>
                      </el-timeline-item>
                    </el-timeline>

                    <!-- 加载更多按钮 -->
                    <div v-if="customerActivities.length > 0" class="load-more-container">
                      <el-button
                        v-if="activitiesPage.hasMore"
                        type="primary"
                        link
                        @click="loadMoreActivities"
                        :loading="activitiesLoading"
                        class="load-more-btn"
                      >
                        {{ activitiesLoading ? '加载中...' : '加载更多' }}
                      </el-button>
                      <div v-else-if="activitiesPage.total > activitiesPage.size" class="no-more-data">
                        <span>已加载全部 {{ activitiesPage.total }} 条记录</span>
                      </div>
                    </div>

                    <!-- 空状态占位 -->
                    <div v-else class="empty-activities">
                      <el-empty description="暂无客户动态" :image-size="80">
                        <template #image>
                          <el-icon :size="80" style="color: #c0c4cc"><Document /></el-icon>
                        </template>
                        <template #description>
                          <span style="color: #909399; font-size: 14px">该客户暂无动态记录</span>
                        </template>
                      </el-empty>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 个人信息选项卡 -->
            <el-tab-pane label="个人信息" name="personalInfo">
              <div class="personal-info-container">
                <div class="personal-info-content">
                  <!-- 基本信息卡片 -->
                  <div class="info-card">
                    <div class="card-header">
                      <h3 class="card-title">基本信息</h3>
                    </div>
                    <div class="card-body">
                      <div class="info-grid">
                        <div class="info-item">
                          <label class="info-label">用户昵称</label>
                          <div class="info-value">{{ currentArchiveUser?.userName || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">微信账号</label>
                          <div class="info-value">{{ currentArchiveUser?.wxAccount || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">用户类型</label>
                          <div class="info-value">
                            <el-tag :type="currentArchiveUser?.type === '1' ? 'success' : 'info'" size="small">
                              {{ currentArchiveUser?.type === '1' ? '好友' : '非好友' }}
                            </el-tag>
                          </div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">备注信息</label>
                          <div class="info-value">{{ currentArchiveUser?.remark || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">新增时间</label>
                          <div class="info-value">{{ currentArchiveUser?.createTime || '-' }}</div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 详细信息卡片 -->
                  <div class="info-card">
                    <div class="card-header">
                      <h3 class="card-title">详细信息</h3>
                    </div>
                    <div class="card-body">
                      <div class="info-grid">
                        <div class="info-item">
                          <label class="info-label">用户年龄</label>
                          <div class="info-value">{{ currentArchiveUser?.userAge || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">用户生日</label>
                          <div class="info-value">{{ currentArchiveUser?.userBirthday || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">手机号码</label>
                          <div class="info-value">{{ currentArchiveUser?.userPhone || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">邮箱地址</label>
                          <div class="info-value">{{ currentArchiveUser?.userEmail || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">QQ号码</label>
                          <div class="info-value">{{ currentArchiveUser?.userQq || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">详细地址</label>
                          <div class="info-value">{{ currentArchiveUser?.userAddress || '-' }}</div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 地区信息卡片 -->
                  <div class="info-card">
                    <div class="card-header">
                      <h3 class="card-title">地区信息</h3>
                    </div>
                    <div class="card-body">
                      <div class="info-grid">
                        <div class="info-item">
                          <label class="info-label">省份</label>
                          <div class="info-value">{{ currentArchiveUser?.userProName || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">城市</label>
                          <div class="info-value">{{ currentArchiveUser?.userCityName || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">区县</label>
                          <div class="info-value">{{ currentArchiveUser?.userCountyName || '-' }}</div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 业务信息卡片 -->
                  <div class="info-card">
                    <div class="card-header">
                      <h3 class="card-title">业务信息</h3>
                    </div>
                    <div class="card-body">
                      <div class="info-grid">
                        <div class="info-item">
                          <label class="info-label">客户来源</label>
                          <div class="info-value">{{ currentArchiveUser?.userCustomerSource || '-' }}</div>
                        </div>
                        <!-- <div class="info-item">
                          <label class="info-label">分配员工</label>
                          <div class="info-value">{{ currentArchiveUser?.userAssignedEmployee || '-' }}</div>
                        </div> -->
                        <div class="info-item">
                          <label class="info-label">用户描述</label>
                          <div class="info-value">{{ currentArchiveUser?.userDescription || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">购买记录</label>
                          <div class="info-value">
                            <el-tag type="primary" size="small"> {{ currentArchiveUser?.purchaseRecordCnt || 0 }} 条记录 </el-tag>
                          </div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">用药提醒</label>
                          <div class="info-value">
                            <el-tag :type="currentArchiveUser?.medicationReminderCnt ? 'success' : 'info'" size="small">
                              {{ currentArchiveUser?.medicationReminderCnt ? '已配置' : '未配置' }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 标签信息卡片 -->
                  <div class="info-card" v-if="currentArchiveUser?.labels && currentArchiveUser.labels.length > 0">
                    <div class="card-header">
                      <h3 class="card-title">用户标签</h3>
                    </div>
                    <div class="card-body">
                      <div class="tags-container">
                        <el-tag v-for="tag in currentArchiveUser.labels" :key="tag.id" type="primary" size="small" class="tag-item">
                          {{ tag.label_name }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 用药提醒选项卡 -->
            <el-tab-pane label="用药提醒" name="medicationReminder">
              <div class="medication-reminder-container">
                <div class="medication-reminder-content">
                  <!-- 基本信息卡片 -->
                  <div class="info-card" v-if="customerMedicationReminder">
                    <div class="card-header">
                      <h3 class="card-title">基本信息</h3>
                    </div>
                    <div class="card-body">
                      <div class="info-grid">
                        <div class="info-item">
                          <label class="info-label">产品名称</label>
                          <div class="info-value">{{ customerMedicationReminder.productName || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">状态</label>
                          <div class="info-value">
                            <el-tag :type="customerMedicationReminder.status === '0' ? 'success' : 'danger'" size="small">
                              {{ customerMedicationReminder.status === '0' ? '启用' : '停用' }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 提醒设置卡片 -->
                  <div class="info-card" v-if="customerMedicationReminder">
                    <div class="card-header">
                      <h3 class="card-title">提醒信息</h3>
                    </div>
                    <div class="card-body">
                      <div class="info-grid">
                        <div class="info-item">
                          <label class="info-label">
                            每天次数
                            <el-tooltip
                              v-if="customerMedicationReminder.triple && customerMedicationReminder.day === 0"
                              :content="getIntervalDaysTip(customerMedicationReminder.day || 0, customerMedicationReminder.triple || 1)"
                              placement="top"
                            >
                              <el-icon class="info-tip-icon"><QuestionFilled /></el-icon>
                            </el-tooltip>
                          </label>
                          <div class="info-value">{{ customerMedicationReminder.triple || '-' }}次</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">间隔天数</label>
                          <div class="info-value">
                            {{ customerMedicationReminder.day === 0 ? '每天' : `每${customerMedicationReminder.day}天` }}
                          </div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">用药截至日期</label>
                          <div class="info-value">{{ customerMedicationReminder.deadline || '-' }}</div>
                        </div>
                        <div class="info-item">
                          <label class="info-label">是否通知客服</label>
                          <div class="info-value">
                            <el-tag :type="customerMedicationReminder.customerServiceStatus === '0' ? 'success' : 'warning'" size="small">
                              {{ customerMedicationReminder.customerServiceStatus === '0' ? '是' : '否' }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 客服设置卡片 -->
                  <div class="info-card" v-if="customerMedicationReminder">
                    <div class="card-header">
                      <h3 class="card-title">所属客服</h3>
                    </div>
                    <div class="card-body">
                      <div class="info-item">
                        <!-- <label class="info-label">所属客服</label> -->
                        <div class="info-value">
                          <div
                            v-if="customerMedicationReminder.customerServiceList && customerMedicationReminder.customerServiceList.length > 0"
                            class="tags-container"
                          >
                            <el-tag
                              v-for="service in customerMedicationReminder.customerServiceList"
                              :key="service.customerService"
                              size="small"
                              class="tag-item service-tag"
                            >
                              {{ service.customerServiceName }}
                            </el-tag>
                          </div>
                          <span v-else>-</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 提醒内容卡片 -->
                  <div class="info-card" v-if="customerMedicationReminder && customerMedicationReminder.message">
                    <div class="card-header">
                      <h3 class="card-title">提醒内容</h3>
                    </div>
                    <div class="card-body">
                      <div class="info-item">
                        <!-- <label class="info-label">消息内容</label> -->
                        <div class="info-value">
                          <div class="message-content">
                            {{ customerMedicationReminder.message }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 暂无配置提示 -->
                  <div v-if="!customerMedicationReminder" class="empty-medication-reminder">
                    <el-empty description="暂无用药提醒配置" :image-size="80">
                      <template #image>
                        <el-icon :size="80" style="color: #c0c4cc"><Document /></el-icon>
                      </template>
                      <template #description>
                        <span style="color: #909399; font-size: 14px">该客户暂未配置用药提醒</span>
                      </template>
                    </el-empty>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 购买记录选项卡 -->
            <el-tab-pane label="购买记录" name="purchaseRecord">
              <div class="purchase-record-tab-container">
                <!-- 筛选条件区域 -->
                <div class="purchase-record-filter">
                  <filter-form
                    labelWidth="120px"
                    v-model="archivePurchaseRecordFilterForm"
                    :form-items="archivePurchaseRecordFormItems"
                    @search="handleArchivePurchaseRecordSearch"
                    @reset="resetArchivePurchaseRecordFilter"
                  />
                </div>

                <!-- 记录列表 -->
                <div class="purchase-record-table-section">
                  <el-table :data="archivePurchaseRecordList" border style="width: 100%" v-loading="archivePurchaseRecordLoading" class="custom-table">
                    <el-table-column type="index" label="序号" width="60" align="center" />
                    <el-table-column prop="shopName" label="店铺名称+平台" min-width="150" show-overflow-tooltip />
                    <el-table-column prop="orderNo" label="订单号" min-width="120" show-overflow-tooltip />
                    <el-table-column prop="receiverName" label="收件人姓名" min-width="100" show-overflow-tooltip />
                    <el-table-column prop="receiverPhone" label="收件人手机号" min-width="120" show-overflow-tooltip />
                    <el-table-column prop="orderDate" label="下单日期" min-width="120" show-overflow-tooltip>
                      <template #default="{ row }">
                        {{ row.orderDate ? dayjs(row.orderDate).format('YYYY-MM-DD') : '-' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="productName" label="产品名称" min-width="150" show-overflow-tooltip />
                    <el-table-column prop="productCode" label="产品货号/编码" min-width="120" show-overflow-tooltip />
                    <el-table-column prop="productSpec" label="购买规格" min-width="100" show-overflow-tooltip />
                    <el-table-column prop="quantity" label="购买数量" min-width="80" align="center" />
                    <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip>
                      <template #default="{ row }">
                        <span>{{ row.remark || '-' }}</span>
                      </template>
                    </el-table-column>
                  </el-table>

                  <!-- 分页 -->
                  <div class="pagination-container">
                    <el-pagination
                      v-model:current-page="archivePurchaseRecordPage.current"
                      v-model:page-size="archivePurchaseRecordPage.size"
                      :page-sizes="[10, 20, 50, 100]"
                      :total="archivePurchaseRecordPage.total"
                      layout="total, sizes, prev, pager, next, jumper"
                      @size-change="handleArchivePurchaseRecordSizeChange"
                      @current-change="handleArchivePurchaseRecordCurrentChange"
                    />
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 聊天记录选项卡 -->
            <el-tab-pane label="聊天记录" name="chatHistory">
              <div class="chat-history-container">
                <ChatHistory
                  v-if="archiveDialogVisible && activeArchiveTab === 'chatHistory' && currentArchiveUser"
                  ref="chatHistoryRef"
                  :msgprofilewx_id="wxId"
                  :messageContent="{ wx_id: currentArchiveUser.wxAccount }"
                  :nowExprentTag="'好友'"
                  :imageUrlfirst="''"
                  @transcribeAudio="handleTranscribeAudio"
                  @downloadFile="handleDownloadFile"
                  @msgSendMessages="handleChatHistoryMsgSendMessages"
                />
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-dialog>

      <!-- 添加动态对话框 -->
      <el-dialog v-model="addActivityDialogVisible" title="新增客户动态" width="600px" destroy-on-close>
        <el-form :model="addActivityForm" label-width="80px">
          <el-form-item label="动态内容" required>
            <el-input v-model="addActivityForm.remark" type="textarea" :rows="4" placeholder="请输入动态内容" maxlength="2000" show-word-limit />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addActivityDialogVisible = false">取消</el-button>
            <el-button type="primary" :loading="addActivityLoading" @click="handleAddActivity">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 客户详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="客户详情" width="1400px" destroy-on-close class="customer-dialog editDialog">
        <div class="detail-content">
          <!-- 客户信息 -->
          <div class="detail-section">
            <h3 class="section-title">客户信息</h3>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="detail-label">客户名称</span>
                <span class="detail-value">{{ customerDetail?.userName || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">客户类型</span>
                <span class="detail-value">
                  <el-tag :type="customerDetail?.type === '1' ? 'success' : 'warning'" size="small">
                    {{ customerDetail?.type === '1' ? '好友' : '非好友' }}
                  </el-tag>
                </span>
              </div>
              <div v-if="customerDetail?.type === '1'" class="detail-item">
                <span class="detail-label">微信号</span>
                <span class="detail-value">{{ customerDetail?.wxAccount || '-' }}</span>
              </div>
              <div v-if="customerDetail?.type === '1'" class="detail-item">
                <span class="detail-label">微信备注</span>
                <span class="detail-value">{{ customerDetail?.remark || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">年龄</span>
                <span class="detail-value">
                  {{
                    customerDetail?.userAge == 0 || customerDetail?.userAge === undefined || customerDetail?.userAge === null ? '-' : customerDetail?.userAge
                  }}
                </span>
              </div>
              <div class="detail-item">
                <span class="detail-label">电话</span>
                <span class="detail-value">{{ customerDetail?.userPhone || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">QQ</span>
                <span class="detail-value">{{ customerDetail?.userQq || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">邮箱</span>
                <span class="detail-value">{{ customerDetail?.userEmail || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">生日</span>
                <span class="detail-value">{{ customerDetail?.userBirthday || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">新增时间</span>
                <span class="detail-value">{{ customerDetail?.userCreateTime || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">更新时间</span>
                <span class="detail-value">{{ customerDetail?.userInfoUpdateTime || '-' }}</span>
              </div>
              <div class="detail-item detail-item-full">
                <span class="detail-label">标签</span>
                <div class="detail-value">
                  <div class="tag-list">
                    <template v-if="customerDetail?.labels && customerDetail.labels.length > 0">
                      <el-tag v-for="label in customerDetail.labels" :key="label.id" class="tag-item" size="small">
                        {{ label.label_name }}
                      </el-tag>
                    </template>
                    <template v-else> - </template>
                  </div>
                </div>
              </div>
              <div class="detail-item detail-item-full">
                <span class="detail-label">地区</span>
                <span class="detail-value">{{ formatAreaDisplay(customerDetail?.userArea, customerDetail) || '-' }}</span>
              </div>
              <div class="detail-item detail-item-full">
                <span class="detail-label">详细地址</span>
                <span class="detail-value">{{ customerDetail?.userAddress || '-' }}</span>
              </div>
              <div class="detail-item detail-item-full">
                <span class="detail-label">描述</span>
                <span class="detail-value">{{ customerDetail?.userDescription || '-' }}</span>
              </div>
            </div>
          </div>

          <!-- 用药提醒信息（仅好友显示） -->
          <div v-if="customerDetail?.type === '1'" class="detail-section">
            <h3 class="section-title">用药提醒</h3>
            <div v-if="customerMedicationReminder" class="detail-grid">
              <div class="detail-item">
                <span class="detail-label">产品名称</span>
                <span class="detail-value">{{ customerMedicationReminder.productName || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">提醒间隔</span>
                <span class="detail-value">{{ customerMedicationReminder.day === 0 ? '每天' : `每${customerMedicationReminder.day}天` }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">每日次数</span>
                <span class="detail-value">{{ customerMedicationReminder.triple || '-' }}次</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">截止日期</span>
                <span class="detail-value">{{ customerMedicationReminder.deadline || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">提醒状态</span>
                <span class="detail-value">
                  <el-tag :type="customerMedicationReminder.status === '1' ? 'success' : 'danger'" size="small">
                    {{ customerMedicationReminder.status === '1' ? '启用' : '停用' }}
                  </el-tag>
                </span>
              </div>
              <div class="detail-item">
                <span class="detail-label">客服通知</span>
                <span class="detail-value">
                  <el-tag :type="customerMedicationReminder.customerServiceStatus === '0' ? 'success' : 'warning'" size="small">
                    {{ customerMedicationReminder.customerServiceStatus === '0' ? '启用' : '停用' }}
                  </el-tag>
                </span>
              </div>
              <div
                class="detail-item detail-item-full"
                v-if="customerMedicationReminder.customerServiceList && customerMedicationReminder.customerServiceList.length > 0"
              >
                <span class="detail-label">所属客服</span>
                <div class="detail-value">
                  <div class="customer-service-list">
                    <el-tag v-for="service in customerMedicationReminder.customerServiceList" :key="service.customerService" size="small" class="service-tag">
                      {{ service.customerServiceName }}
                    </el-tag>
                  </div>
                </div>
              </div>
              <div class="detail-item detail-item-full" v-if="customerMedicationReminder.message">
                <span class="detail-label">提醒内容</span>
                <span class="detail-value">{{ customerMedicationReminder.message }}</span>
              </div>
            </div>
            <div v-else class="no-medication">
              <el-text type="info">暂无用药提醒设置</el-text>
            </div>
          </div>

          <!-- 非好友提示 -->
          <div v-else class="detail-section">
            <h3 class="section-title">功能说明</h3>
            <div class="detail-grid">
              <div class="detail-item detail-item-full">
                <span class="detail-label">提醒功能</span>
                <div class="detail-value">
                  <el-alert title="非好友客户无法设置用药提醒" type="info" :closable="false" show-icon />
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>

      <!-- 编辑客户对话框 -->
      <el-dialog v-model="editDialogVisible" :title="editMode === 'add' ? '新增客户' : '编辑客户'" width="1200px" destroy-on-close class="customer-edit-dialog">
        <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="110px" class="customer-edit-form">
          <!-- 个人信息 -->
          <div class="form-section">
            <h3 class="section-title">个人信息</h3>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="客户名称" prop="customerName">
                  <el-input v-model="editForm.customerName" :disabled="editMode === 'edit' && editForm.type === '1'" placeholder="请输入客户名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="editMode === 'edit' && editForm.type === '1'">
                <el-form-item label="微信号" prop="wxAccount">
                  <el-input v-model="editForm.wxAccount" disabled placeholder="请输入微信号" />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="editMode === 'edit'">
                <el-form-item label="类型" prop="type">
                  <el-select disabled v-model="editForm.type" placeholder="请选择类型" style="width: 100%">
                    <el-option label="好友" value="1" />
                    <el-option label="非好友" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="editMode === 'edit' && editForm.type === '1'">
                <el-form-item label="微信备注" prop="remark">
                  <el-input v-model="editForm.remark" placeholder="请输入微信备注" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="年龄" prop="userAge">
                  <el-input type="number" placeholder="请输入年龄" v-model="editForm.userAge" :max="120" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="生日" prop="userBirthday">
                  <el-date-picker v-model="editForm.userBirthday" type="date" placeholder="请选择生日" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="地区" prop="userArea">
                  <area-select v-model="editForm.userArea" @change="handleAreaChange" />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="详细地址" prop="userAddress">
                  <el-input v-model="editForm.userAddress" placeholder="请输入详细地址" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 联系方式 -->
          <div class="form-section">
            <h3 class="section-title">联系方式</h3>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="电话" prop="userPhone">
                  <el-input v-model="editForm.userPhone" placeholder="请输入电话号码" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="邮箱" prop="userEmail">
                  <el-input v-model="editForm.userEmail" placeholder="请输入邮箱地址" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="QQ" prop="userQq">
                  <el-input v-model="editForm.userQq" placeholder="请输入QQ号码" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 其他信息 -->
          <div class="form-section">
            <h3 class="section-title">其他信息</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所属行业" prop="industry">
                  <el-input v-model="editForm.industry" placeholder="请输入所属行业" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户来源" prop="userCustomerSource">
                  <el-input v-model="editForm.userCustomerSource" placeholder="请输入客户来源" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="描述" prop="userDescription">
                  <el-input v-model="editForm.userDescription" type="textarea" :rows="4" placeholder="请输入客户描述" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit" :loading="editLoading">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 记录对话框 -->
      <el-dialog v-model="purchaseRecordDialogVisible" title="购买记录" width="90%" destroy-on-close class="purchase-record-dialog">
        <div class="purchase-record-container">
          <!-- 筛选条件区域 -->
          <filter-form
            labelWidth="120px"
            v-model="purchaseRecordFilterForm"
            :form-items="purchaseRecordFormItems"
            @search="handlePurchaseRecordSearch"
            @reset="resetPurchaseRecordFilter"
          />

          <div class="operation-section">
            <el-button type="primary" @click="handleAddPurchaseRecord">新增记录</el-button>
          </div>

          <!-- 主要内容区域 -->
          <div class="main-content">
            <!-- 记录列表 -->
            <div class="table-section">
              <el-table :data="purchaseRecordList" border style="width: 100%" v-loading="purchaseRecordLoading" class="custom-table">
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="shopName" label="店铺名称+平台" min-width="150" show-overflow-tooltip />
                <el-table-column prop="orderNo" label="订单号" min-width="120" show-overflow-tooltip />
                <el-table-column prop="receiverName" label="收件人姓名" min-width="100" show-overflow-tooltip />
                <el-table-column prop="receiverPhone" label="收件人手机号" min-width="120" show-overflow-tooltip />
                <el-table-column prop="orderDate" label="下单日期" min-width="120" show-overflow-tooltip>
                  <template #default="{ row }">
                    {{ row.orderDate ? dayjs(row.orderDate).format('YYYY-MM-DD') : '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="productName" label="产品名称" min-width="150" show-overflow-tooltip />
                <el-table-column prop="productCode" label="产品货号/编码" min-width="120" show-overflow-tooltip />
                <el-table-column prop="productSpec" label="购买规格" min-width="100" show-overflow-tooltip />
                <el-table-column prop="quantity" label="购买数量" min-width="80" align="center" />
                <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip>
                  <template #default="{ row }">
                    <span>{{ row.remark || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right" align="center">
                  <template #default="{ row }">
                    <el-button type="primary" link @click="handleEditPurchaseRecord(row)">编辑</el-button>
                    <el-button type="danger" link @click="handleDeletePurchaseRecord(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <!-- 记录分页 -->
          <pagination
            v-model:current-page="purchaseRecordPage.current"
            v-model:page-size="purchaseRecordPage.size"
            :total="purchaseRecordTotal"
            @pagination="handlePurchaseRecordPagination"
          />
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="purchaseRecordDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 用药提醒对话框 -->
      <el-dialog v-model="medicationReminderDialogVisible" title="设置提醒" width="900px" destroy-on-close class="medication-reminder-dialog">
        <el-form
          :model="medicationReminderForm"
          :rules="medicationReminderRules"
          ref="medicationReminderFormRef"
          label-width="110px"
          v-loading="medicationReminderLoading"
          class="medication-reminder-form"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="medicationReminderForm.productName" placeholder="请输入产品名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="medicationReminderForm.status">
                    <el-radio value="0">启用</el-radio>
                    <el-radio value="1">停用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 客户设置 -->
          <div class="form-section">
            <h3 class="section-title">客户设置</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="triple">
                  <template #label>
                    每天次数
                    <el-tooltip
                      v-if="medicationReminderForm.triple && dayType === 'daily'"
                      :content="getIntervalDaysTip(medicationReminderForm.day || 0, medicationReminderForm.triple || 1)"
                      placement="top"
                    >
                      <el-icon class="form-tip-icon"><QuestionFilled /></el-icon>
                    </el-tooltip>
                  </template>
                  <el-input-number v-model="medicationReminderForm.triple" :min="1" :max="3" placeholder="请输入每天次数" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="间隔天数" prop="day">
                  <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap">
                    <el-radio-group v-model="dayType" @change="handleDayTypeChange">
                      <el-radio value="daily">每天</el-radio>
                      <el-radio value="custom">自定义</el-radio>
                    </el-radio-group>
                    <el-input-number
                      v-if="dayType === 'custom'"
                      v-model="customDayValue"
                      :min="1"
                      placeholder="请输入"
                      style="width: 100px"
                      @change="handleCustomDayChange"
                    />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="提醒内容" prop="message">
                  <el-input v-model="medicationReminderForm.message" type="textarea" :rows="4" placeholder="请输入提醒内容" maxlength="2000" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 客服设置 -->
          <div class="form-section">
            <h3 class="section-title">客服设置</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用药截至日期" prop="deadline">
                  <el-date-picker
                    v-model="medicationReminderForm.deadline"
                    type="date"
                    placeholder="请选择用药截至日期"
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否通知客服" prop="customerServiceStatus">
                  <el-radio-group v-model="medicationReminderForm.customerServiceStatus">
                    <el-radio value="0">是</el-radio>
                    <el-radio value="1">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="所属客服" prop="customerService">
                  <friend-tag-input
                    :selected-friends="selectedCustomerServiceFriends"
                    placeholder="请选择所属客服"
                    @click="customerServiceFriendSelectDialogVisible = true"
                    @remove="handleRemoveCustomerServiceFriend"
                  />
                  <friend-select-dialog
                    v-model="customerServiceFriendSelectDialogVisible"
                    :multiple="true"
                    :selected-friends="selectedCustomerServiceFriends.map((f) => f.wx_id)"
                    title="选择所属客服"
                    @confirm="handleCustomerServiceFriendSelectConfirm"
                    @cancel="customerServiceFriendSelectDialogVisible = false"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="medicationReminderDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitMedicationReminder" :loading="medicationReminderLoading">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 购买记录编辑对话框 -->
      <el-dialog
        v-model="purchaseRecordEditDialogVisible"
        :title="purchaseRecordEditMode === 'add' ? '新增购买记录' : '编辑购买记录'"
        width="900px"
        destroy-on-close
        class="purchase-record-dialog"
      >
        <el-form :model="purchaseRecordForm" :rules="purchaseRecordRules" ref="purchaseRecordFormRef" label-width="110px" class="purchase-record-form">
          <!-- 订单信息 -->
          <div class="form-section">
            <h3 class="section-title">订单信息</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="店铺名称" prop="shopName">
                  <el-input v-model="purchaseRecordForm.shopName" placeholder="请输入店铺名称+平台" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单号" prop="orderNo">
                  <el-input v-model="purchaseRecordForm.orderNo" placeholder="请输入订单号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="下单日期" prop="orderDate">
                  <el-date-picker v-model="purchaseRecordForm.orderDate" type="date" placeholder="请选择下单日期" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 收件人信息 -->
          <div class="form-section">
            <h3 class="section-title">收件人信息</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="收件人姓名" prop="receiverName">
                  <el-input v-model="purchaseRecordForm.receiverName" placeholder="请输入收件人姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收件人手机" prop="receiverPhone">
                  <el-input v-model="purchaseRecordForm.receiverPhone" placeholder="请输入收件人手机号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="收件人地址" prop="receiverAddr">
                  <el-input v-model="purchaseRecordForm.receiverAddr" placeholder="请输入收件人地址" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 商品信息 -->
          <div class="form-section">
            <h3 class="section-title">商品信息</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="purchaseRecordForm.productName" placeholder="请输入产品名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品货号" prop="productCode">
                  <el-input v-model="purchaseRecordForm.productCode" placeholder="请输入产品货号/编码" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="购买规格" prop="productSpec">
                  <el-input v-model="purchaseRecordForm.productSpec" placeholder="请输入购买规格" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="购买数量" prop="quantity">
                  <el-input-number v-model="purchaseRecordForm.quantity" :min="1" placeholder="请输入购买数量" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="purchaseRecordForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息..." maxlength="500" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="purchaseRecordEditDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitPurchaseRecord" :loading="purchaseRecordEditLoading">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Document, QuestionFilled } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import {
  getWechatUserList,
  addWechatUser,
  updateWechatUser,
  deleteWechatUser,
  getPurchaseRecordList,
  addPurchaseRecord,
  updatePurchaseRecord,
  deletePurchaseRecord,
  getMedicationReminderList,
  updateMedicationReminder,
  type PurchaseRecord,
  type MedicationReminder
} from '@/api/userMange/userMangePath';
import { msgSendMessages, getCustomerLogList, addCustomerLog } from '@/api/wechat';
import FriendTagInput from '@/components/FriendSelect/FriendTagInput.vue';
import FriendSelectDialog from '@/components/FriendSelect/FriendSelectDialog.vue';
import AreaSelect from '@/components/AreaSelect/index.vue';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';
import AiWechatInfo from '@/components/AiWechatInfo/index.vue';
import ChatHistory from '@/views/weChat/components/ChatHistory.vue';
import { wechatEmojiMap } from '@/utils/wechatEmojiMap';
import dayjs from 'dayjs';

interface SearchParams {
  wxId: string;
  userName: string;
  remark: string;
  wxAccount: string;
  type: string;
  current: number;
  size: number;
}

interface WechatUser {
  id: string;
  wechatAccountId: string;
  myWxId: string;
  userOpenId: string;
  userWechatUserId: string;
  userName: string;
  userAvatarUrl: string;
  userEmail: string;
  userPhone: string;
  userCreateTime: string;
  userInfoUpdateTime: string;
  remark: string;
  wxAccount: string;
  userAge: number | undefined;
  userBirthday: string;
  userQq: string;
  userArea?: string[]; // 地区选择
  userProName?: string; // 客户省份名称
  userCityName?: string; // 客户地市名称
  userCountyName?: string; // 客户区/县名称
  userPro?: string; // 客户省份编码
  userCity?: string; // 客户地市编码
  userCounty?: string; // 客户区/县编码
  userAddress: string;
  userDescription: string;
  userCustomerSource: string;
  userAssignedEmployee: string;
  industry: string; // 所属行业
  endMessageTime: string; // 最后联系时间
  type: string; // 区分是否好友：1-好友，2-非好友
  purchaseRecordCnt?: number; // 购买记录条数
  medicationReminderCnt?: number; // 是否配置用药提醒（0-未配置，1-已配置）
  labels?: Array<{ id: string | number; label_name: string }>; // 标签列表
}

interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

interface Friend {
  wx_id: string;
  nick_name: string;
  first_nick_name: string;
  avatar: string;
  gender: string;
  labels: Array<{ id: string; label_name: string }>;
}

// 消息项接口
interface MessageItem {
  message_content?: string;
  message_type: number;
  direction: string;
  senderUrl: string;
  messageId: string;
  isShowCheck?: boolean;
  isLoading?: boolean;
  aiMessage?: string;
  ai_message?: string;
}

interface TableItem {
  userName: string;
  wxAccount: string;
  avatarUrl: string;
  labels: Array<{ id: number; label_name: string }>;
  createTime: string;
  updateTime: string;
  customer_id: string;
  userAge: number;
  userArea?: string[]; // 地区选择
  userProName?: string; // 客户省份名称
  userCityName?: string; // 客户地市名称
  userCountyName?: string; // 客户区/县名称
  userPro?: string; // 客户省份编码
  userCity?: string; // 客户地市编码
  userCounty?: string; // 客户区/县编码
  userAddress: string;
  userBirthday: string;
  userDescription: string;
  userQq: string;
  userPhone: string;
  userEmail: string;
  userCustomerSource: string;
  userAssignedEmployee: string;
  industry: string; // 所属行业
  endMessageTime: string; // 最后联系时间
  gender: string;
  remark: string;
  type: string; // 区分是否好友：1-好友，2-非好友
  purchaseRecordCnt?: number; // 购买记录条数
  medicationReminderCnt?: string; // 用药提醒状态
}

interface PageResult<T> {
  records: T[];
  total: number;
  size: number;
  current: number;
  pages: number;
}

// 从本地存储获取wxId
const wxId = ref(localStorage.getItem('msgprofile') ? JSON.parse(localStorage.getItem('msgprofile')!).wx_id : '');

// 筛选表单
const filterForm = reactive({
  customerName: '',
  remark: '',
  wxAccount: '',
  type: '',
  industry: '',
  userCustomerSource: '',
  endMessageTime: []
});

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    label: '客户名称',
    prop: 'customerName',
    type: 'input',
    placeholder: '请输入客户名称'
  },
  {
    label: '微信号',
    prop: 'wxAccount',
    type: 'input',
    placeholder: '请输入微信号'
  },
  {
    label: '微信备注',
    prop: 'remark',
    type: 'input',
    placeholder: '请输入微信备注'
  },
  {
    label: '好友类型',
    prop: 'type',
    type: 'select',
    placeholder: '请选择好友类型',
    options: [
      { label: '全部', value: '' },
      { label: '好友', value: '1' },
      { label: '非好友', value: '2' }
    ]
  },
  {
    label: '所属行业',
    prop: 'industry',
    type: 'input',
    placeholder: '请输入所属行业'
  },
  {
    label: '客户来源',
    prop: 'userCustomerSource',
    type: 'input',
    placeholder: '请输入客户来源'
  },
  {
    label: '最后联系时间',
    prop: 'endMessageTime',
    type: 'daterange',
    placeholder: '请选择时间范围'
  }
]);

// 表格数据
const tableData = ref<TableItem[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 详情对话框
const detailDialogVisible = ref(false);
const customerDetail = ref<WechatUser | null>(null);
const customerMedicationReminder = ref<MedicationReminder | null>(null);

// 档案对话框
const archiveDialogVisible = ref(false);
const activeArchiveTab = ref('dynamics');
const currentArchiveUser = ref<TableItem | null>(null);
const chatHistoryRef = ref<InstanceType<typeof ChatHistory> | null>(null);

// 客户动态相关
const customerActivities = ref<any[]>([]);
const activitiesLoading = ref(false);
const activitiesPage = ref({
  current: 1,
  size: 20,
  total: 0,
  hasMore: true
});
const refreshingActivities = ref(false);
const refreshCountdown = ref(0);
let refreshTimer: NodeJS.Timeout | null = null;

// 新增动态对话框
const addActivityDialogVisible = ref(false);
const addActivityLoading = ref(false);
const addActivityForm = reactive({
  remark: ''
});

// 编辑客户对话框
const editDialogVisible = ref(false);
const editFormRef = ref<FormInstance>();
const editLoading = ref(false);
const editMode = ref<'add' | 'edit'>('edit');

// 编辑表单数据
const editForm = reactive({
  id: '',
  customerName: '',
  wxAccount: '',
  userAge: undefined as number | undefined,
  userArea: [] as string[], // 地区选择
  userProName: '', // 客户省份名称
  userCityName: '', // 客户地市名称
  userCountyName: '', // 客户区/县名称
  userPro: '', // 客户省份编码
  userCity: '', // 客户地市编码
  userCounty: '', // 客户区/县编码
  userAddress: '',
  userBirthday: '',
  userDescription: '',
  userQq: '',
  userPhone: '',
  userEmail: '',
  userCustomerSource: '',
  userAssignedEmployee: '',
  industry: '', // 所属行业
  remark: '',
  type: '1' // 默认为好友
});

// 编辑表单验证规则
const editFormRules = computed<FormRules>(() => ({
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  wxAccount: editMode.value === 'edit' ? [{ required: true, message: '请输入微信号', trigger: 'blur' }] : [],
  type: editMode.value === 'edit' ? [{ required: true, message: '请选择类型', trigger: 'change' }] : [],
  userPhone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  userEmail: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  userQq: [{ pattern: /^[1-9][0-9]{4,}$/, message: '请输入正确的QQ号码', trigger: 'blur' }]
}));

// 记录相关变量
const purchaseRecordDialogVisible = ref(false);
const purchaseRecordList = ref<PurchaseRecord[]>([]);
const purchaseRecordLoading = ref(false);
const purchaseRecordPage = reactive({ current: 1, size: 10 });
const purchaseRecordTotal = ref(0);

// 档案购买记录选项卡相关变量
const archivePurchaseRecordList = ref<PurchaseRecord[]>([]);
const archivePurchaseRecordLoading = ref(false);
const archivePurchaseRecordPage = reactive({ current: 1, size: 10, total: 0 });
const currentUserWxId = ref('');

// 记录筛选表单
const purchaseRecordFilterForm = reactive({
  shopName: '',
  orderNo: '',
  receiverName: '',
  receiverPhone: '',
  productName: '',
  productCode: '',
  remark: '',
  orderDate: ''
});

// 档案购买记录筛选表单
const archivePurchaseRecordFilterForm = reactive({
  shopName: '',
  orderNo: '',
  receiverName: '',
  receiverPhone: '',
  productName: '',
  productCode: '',
  remark: '',
  orderDate: ''
});

// 记录筛选表单项配置
const purchaseRecordFormItems = computed<FormItem[]>(() => [
  {
    type: 'input',
    label: '店铺名称',
    prop: 'shopName',
    placeholder: '请输入店铺名称'
  },
  {
    type: 'input',
    label: '订单号',
    prop: 'orderNo',
    placeholder: '请输入订单号'
  },
  {
    type: 'input',
    label: '收件人姓名',
    prop: 'receiverName',
    placeholder: '请输入收件人姓名'
  },
  {
    type: 'input',
    label: '收件人手机号',
    prop: 'receiverPhone',
    placeholder: '请输入收件人手机号'
  },
  {
    type: 'input',
    label: '产品名称',
    prop: 'productName',
    placeholder: '请输入产品名称'
  },
  {
    type: 'input',
    label: '产品货号',
    prop: 'productCode',
    placeholder: '请输入产品货号'
  },
  {
    type: 'input',
    label: '备注',
    prop: 'remark',
    placeholder: '请输入备注'
  },
  {
    type: 'date',
    label: '下单日期',
    prop: 'orderDate',
    placeholder: '请选择下单日期'
  }
]);

// 档案购买记录筛选表单项配置
const archivePurchaseRecordFormItems = computed<FormItem[]>(() => [
  {
    type: 'input',
    label: '店铺名称',
    prop: 'shopName',
    placeholder: '请输入店铺名称'
  },
  {
    type: 'input',
    label: '订单号',
    prop: 'orderNo',
    placeholder: '请输入订单号'
  },
  {
    type: 'input',
    label: '收件人姓名',
    prop: 'receiverName',
    placeholder: '请输入收件人姓名'
  },
  {
    type: 'input',
    label: '收件人手机号',
    prop: 'receiverPhone',
    placeholder: '请输入收件人手机号'
  },
  {
    type: 'input',
    label: '产品名称',
    prop: 'productName',
    placeholder: '请输入产品名称'
  },
  {
    type: 'input',
    label: '产品货号',
    prop: 'productCode',
    placeholder: '请输入产品货号'
  },
  {
    type: 'input',
    label: '备注',
    prop: 'remark',
    placeholder: '请输入备注'
  },
  {
    type: 'date',
    label: '下单日期',
    prop: 'orderDate',
    placeholder: '请选择下单日期'
  }
]);

// 记录编辑对话框
const purchaseRecordEditDialogVisible = ref(false);
const purchaseRecordFormRef = ref<FormInstance>();
const purchaseRecordEditLoading = ref(false);
const purchaseRecordEditMode = ref<'add' | 'edit'>('add');

// 记录表单数据
const purchaseRecordForm = reactive<PurchaseRecord>({
  id: undefined,
  wxId: '',
  myWxId: '',
  shopName: '',
  orderNo: '',
  receiverName: '',
  receiverPhone: '',
  receiverAddr: '',
  orderDate: undefined,
  productName: '',
  productCode: '',
  productSpec: '',
  quantity: undefined,
  remark: ''
});

// 记录表单验证规则
const purchaseRecordRules: FormRules = {
  shopName: [{ required: true, message: '请输入店铺名称+平台', trigger: 'blur' }],
  orderNo: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  receiverName: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
  receiverPhone: [
    { required: true, message: '请输入收件人手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入购买数量', trigger: 'blur' }]
};

// 用药提醒相关变量
const medicationReminderDialogVisible = ref(false);
const medicationReminderFormRef = ref<FormInstance>();
const medicationReminderLoading = ref(false);
const dayType = ref<'daily' | 'custom'>('daily');
const customDayValue = ref<number>();

// 客服好友选择相关变量
const customerServiceFriendSelectDialogVisible = ref(false);
const selectedCustomerServiceFriends = ref<Friend[]>([]);

// 用药提醒表单数据
const medicationReminderForm = reactive<MedicationReminder>({
  id: undefined,
  wxId: '',
  sendWxId: '',
  day: undefined,
  triple: undefined,
  productName: '',
  message: '',
  status: '1',
  customerService: '',
  customerServiceStatus: '0',
  deadline: ''
});

// 用药提醒表单验证规则
const medicationReminderRules = computed<FormRules>(() => ({
  sendWxId: [{ required: true, message: '请输入接收人微信ID', trigger: 'blur' }],
  day: [],
  triple: [{ required: true, message: '请输入每天次数', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  message: [
    { required: true, message: '请输入提醒内容', trigger: 'blur' },
    { max: 2000, message: '提醒内容不能超过2000个字符', trigger: 'blur' }
  ],
  status: [],
  customerService: medicationReminderForm.customerServiceStatus === '0' ? [{ required: true, message: '请选择所属客服', trigger: 'blur' }] : [],
  customerServiceStatus: [],
  deadline: [{ required: true, message: '请选择用药截至日期', trigger: 'change' }]
}));

// 详情表单数据
const detailForm = reactive({
  customerName: '',
  age: undefined as number | undefined,
  phone: '',
  email: '',
  qq: '',
  address: '',
  birthday: '',
  description: ''
});

// 监听 customerDetail 变化
watch(customerDetail, (newVal) => {
  if (newVal) {
    detailForm.customerName = newVal.userName;
    detailForm.age = newVal.userAge;
    detailForm.phone = newVal.userPhone;
    detailForm.email = newVal.userEmail;
    detailForm.qq = newVal.userQq;
    detailForm.address = newVal.userAddress;
    detailForm.birthday = newVal.userBirthday;
    detailForm.description = newVal.userDescription;
  }
});

// 搜索方法
const handleSearch = async (formData?: Record<string, any>) => {
  loading.value = true;
  try {
    // 使用传入的表单数据或当前的表单数据
    const searchData = formData || filterForm;
    const params: SearchParams = {
      wxId: wxId.value,
      userName: searchData.customerName,
      remark: searchData.remark,
      wxAccount: searchData.wxAccount,
      type: searchData.type,
      current: currentPage.value,
      size: pageSize.value
    };

    const res = await getWechatUserList(params);
    const response = res as unknown as ApiResponse<PageResult<TableItem>>;
    if (response.code === 200) {
      tableData.value = response.data.records;
      total.value = response.data.total;
      currentPage.value = response.data.current;
      pageSize.value = response.data.size;
    } else {
      ElMessage.error(response.msg || '获取数据失败');
    }
  } catch (error) {
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选
const resetFilter = () => {
  filterForm.customerName = '';
  filterForm.remark = '';
  filterForm.wxAccount = '';
  filterForm.type = '';
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 分页方法
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};

// 处理筛选条件变化
const handleFilterChange = (val: any) => {
  filterForm.customerName = val.customerName || '';
  filterForm.remark = val.remark || '';
  filterForm.wxAccount = val.wxAccount || '';
  filterForm.type = val.type || '';
};

// 地区代码到名称的映射（可以从后端获取或维护一个静态映射）
const areaCodeToNameMap = ref<Map<string, string>>(new Map());

// 格式化地区显示
const formatAreaDisplay = (areaArray?: string[], customerDetail?: any) => {
  // 优先使用省市区名称字段
  if (customerDetail) {
    const areaNames = [];
    if (customerDetail.userProName) areaNames.push(customerDetail.userProName);
    if (customerDetail.userCityName) areaNames.push(customerDetail.userCityName);
    if (customerDetail.userCountyName) areaNames.push(customerDetail.userCountyName);

    if (areaNames.length > 0) {
      return areaNames.join(' / ');
    }
  }

  // 如果没有名称字段，则使用地区代码转换
  if (!areaArray || areaArray.length === 0) {
    return '';
  }

  // 尝试将地区代码转换为地区名称
  const areaNames = areaArray.map((code) => {
    const name = areaCodeToNameMap.value.get(code);
    return name || code; // 如果找不到名称就显示代码
  });

  return areaNames.join(' / ');
};

// 地区选择变化处理
const handleAreaChange = (value: string[], data: any) => {
  // 保存地区代码到名称的映射
  if (data && data.selectedData && data.selectedData.length > 0) {
    data.selectedData.forEach((area: any) => {
      if (area.areaCode && area.areaName) {
        areaCodeToNameMap.value.set(area.areaCode, area.areaName);
      }
    });
  }

  // 更新表单中的省市区名称和编码
  if (data && data.areaNames) {
    editForm.userProName = data.areaNames.userProName || '';
    editForm.userCityName = data.areaNames.userCityName || '';
    editForm.userCountyName = data.areaNames.userCountyName || '';
  }

  // 更新地区编码（用于提交）
  if (value && value.length > 0) {
    // 假设 value 数组按照 [省编码, 市编码, 区编码] 的顺序
    editForm.userPro = value[0] || '';
    editForm.userCity = value[1] || '';
    editForm.userCounty = value[2] || '';
  } else {
    editForm.userPro = '';
    editForm.userCity = '';
    editForm.userCounty = '';
  }

  console.log('选中的地区:', value, data);
};

// 新增客户
const handleAdd = () => {
  editMode.value = 'add';
  editDialogVisible.value = true;
  Object.assign(editForm, {
    id: '',
    customerName: '',
    wxAccount: '', // 新增时不需要填写，但保留字段
    userAge: undefined,
    userArea: [], // 地区选择
    userProName: '', // 客户省份名称
    userCityName: '', // 客户地市名称
    userCountyName: '', // 客户区/县名称
    userPro: '', // 客户省份编码
    userCity: '', // 客户地市编码
    userCounty: '', // 客户区/县编码
    userAddress: '',
    userBirthday: '',
    userDescription: '',
    userQq: '',
    userPhone: '',
    userEmail: '',
    userCustomerSource: '',
    userAssignedEmployee: '',
    industry: '', // 所属行业
    remark: '',
    type: '' // 新增时不需要设置类型
  });
};

// 编辑客户
const handleEdit = (row: TableItem) => {
  editMode.value = 'edit';
  editDialogVisible.value = true;

  // 构建地区选择数组：根据省市区编码构建
  const userAreaArray: string[] = [];
  if (row.userPro) userAreaArray.push(row.userPro);
  if (row.userCity) userAreaArray.push(row.userCity);
  if (row.userCounty) userAreaArray.push(row.userCounty);

  // 如果有省市区名称，预先保存到映射中
  if (row.userPro && row.userProName) {
    areaCodeToNameMap.value.set(row.userPro, row.userProName);
  }
  if (row.userCity && row.userCityName) {
    areaCodeToNameMap.value.set(row.userCity, row.userCityName);
  }
  if (row.userCounty && row.userCountyName) {
    areaCodeToNameMap.value.set(row.userCounty, row.userCountyName);
  }

  Object.assign(editForm, {
    id: row.customer_id,
    customerName: row.userName,
    wxAccount: row.wxAccount,
    userAge: row.userAge == 0 ? '' : row.userAge,
    userArea: userAreaArray, // 使用构建的地区选择数组
    userProName: row.userProName || '', // 客户省份名称
    userCityName: row.userCityName || '', // 客户地市名称
    userCountyName: row.userCountyName || '', // 客户区/县名称
    userPro: row.userPro || '', // 客户省份编码
    userCity: row.userCity || '', // 客户地市编码
    userCounty: row.userCounty || '', // 客户区/县编码
    userAddress: row.userAddress,
    userBirthday: row.userBirthday,
    userDescription: row.userDescription,
    userQq: row.userQq,
    userPhone: row.userPhone,
    userEmail: row.userEmail,
    userCustomerSource: row.userCustomerSource,
    userAssignedEmployee: row.userAssignedEmployee,
    industry: row.industry || '', // 所属行业
    remark: row.remark,
    type: row.type
  });
};

// 提交编辑
const submitEdit = async () => {
  if (!editFormRef.value) return;
  await editFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        editLoading.value = true;
        const wechatUserData: any = {
          id: editForm.id,
          userName: editForm.customerName,
          userAge: editForm.userAge,
          userArea: editForm.userArea, // 地区选择
          userProName: editForm.userProName, // 客户省份名称
          userCityName: editForm.userCityName, // 客户地市名称
          userCountyName: editForm.userCountyName, // 客户区/县名称
          userPro: editForm.userPro, // 客户省份编码
          userCity: editForm.userCity, // 客户地市编码
          userCounty: editForm.userCounty, // 客户区/县编码
          userAddress: editForm.userAddress,
          userBirthday: editForm.userBirthday ? dayjs(editForm.userBirthday).format('YYYY-MM-DD') : '',
          userDescription: editForm.userDescription,
          userQq: editForm.userQq,
          userPhone: editForm.userPhone,
          userEmail: editForm.userEmail,
          userCustomerSource: editForm.userCustomerSource,
          userAssignedEmployee: editForm.userAssignedEmployee,
          industry: editForm.industry, // 所属行业
          remark: editForm.remark,
          myWxId: wxId.value
        };

        // 只有在编辑模式时才传递 type 和 wxAccount
        if (editMode.value === 'edit') {
          wechatUserData.type = editForm.type;
          wechatUserData.wxAccount = editForm.wxAccount;
        } else if (editMode.value === 'add' && editForm.wxAccount) {
          // 新增时如果有微信号才传递
          wechatUserData.wxAccount = editForm.wxAccount;
        }

        const formData = {
          wechatUser: wechatUserData
        };

        const res = editMode.value === 'add' ? await addWechatUser(formData) : await updateWechatUser(formData);
        const response = res as unknown as ApiResponse<any>;
        if (response.code === 200) {
          ElMessage.success(editMode.value === 'add' ? '新增成功' : '编辑成功');
          editDialogVisible.value = false;
          handleSearch();
        } else {
          ElMessage.error(response.msg || (editMode.value === 'add' ? '新增失败' : '编辑失败'));
        }
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error(editMode.value === 'add' ? '新增失败' : '编辑失败');
      } finally {
        editLoading.value = false;
      }
    }
  });
};

// 记录相关函数
const handlePurchaseRecord = async (row: WechatUser) => {
  currentUserWxId.value = row.wxAccount;
  purchaseRecordDialogVisible.value = true;
  await loadPurchaseRecordList();
};

const loadPurchaseRecordList = async (searchParams?: any) => {
  try {
    purchaseRecordLoading.value = true;
    const params = {
      current: purchaseRecordPage.current,
      size: purchaseRecordPage.size,
      wxId: currentUserWxId.value,
      myWxId: wxId.value, // 添加当前登录用户的微信ID
      ...(searchParams || purchaseRecordFilterForm)
    };

    // 移除空值参数
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });

    const response = await getPurchaseRecordList(params);
    const res = response as unknown as ApiResponse<{ records: PurchaseRecord[]; total: number }>;
    if (res.code === 200) {
      purchaseRecordList.value = res.data.records;
      purchaseRecordTotal.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取记录失败');
    }
  } catch (error) {
    console.error('获取记录失败:', error);
    ElMessage.error('获取记录失败');
  } finally {
    purchaseRecordLoading.value = false;
  }
};

// 记录搜索
const handlePurchaseRecordSearch = async (formData?: Record<string, any>) => {
  purchaseRecordPage.current = 1;
  await loadPurchaseRecordList(formData);
};

// 重置记录筛选条件
const resetPurchaseRecordFilter = () => {
  Object.assign(purchaseRecordFilterForm, {
    shopName: '',
    orderNo: '',
    receiverName: '',
    receiverPhone: '',
    productName: '',
    productCode: '',
    orderDate: ''
  });
  purchaseRecordPage.current = 1;
  loadPurchaseRecordList();
};

const handlePurchaseRecordPagination = () => {
  loadPurchaseRecordList();
};

// 档案购买记录选项卡相关函数
const loadArchivePurchaseRecordList = async (searchParams?: any) => {
  try {
    archivePurchaseRecordLoading.value = true;
    const params = {
      current: archivePurchaseRecordPage.current,
      size: archivePurchaseRecordPage.size,
      wxId: currentArchiveUser.value?.wxAccount,
      myWxId: wxId.value,
      ...(searchParams || archivePurchaseRecordFilterForm)
    };

    // 移除空值参数
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });

    const response = await getPurchaseRecordList(params);
    const res = response as unknown as ApiResponse<{ records: PurchaseRecord[]; total: number }>;
    if (res.code === 200) {
      archivePurchaseRecordList.value = res.data.records;
      archivePurchaseRecordPage.total = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取购买记录失败');
    }
  } catch (error) {
    console.error('获取购买记录失败:', error);
    ElMessage.error('获取购买记录失败');
  } finally {
    archivePurchaseRecordLoading.value = false;
  }
};

// 档案购买记录搜索
const handleArchivePurchaseRecordSearch = async (formData?: Record<string, any>) => {
  archivePurchaseRecordPage.current = 1;
  await loadArchivePurchaseRecordList(formData);
};

// 重置档案购买记录筛选条件
const resetArchivePurchaseRecordFilter = () => {
  Object.assign(archivePurchaseRecordFilterForm, {
    shopName: '',
    orderNo: '',
    receiverName: '',
    receiverPhone: '',
    productName: '',
    productCode: '',
    remark: '',
    orderDate: ''
  });
  archivePurchaseRecordPage.current = 1;
  loadArchivePurchaseRecordList();
};

// 档案购买记录分页处理
const handleArchivePurchaseRecordSizeChange = (size: number) => {
  archivePurchaseRecordPage.size = size;
  archivePurchaseRecordPage.current = 1;
  loadArchivePurchaseRecordList();
};

const handleArchivePurchaseRecordCurrentChange = (current: number) => {
  archivePurchaseRecordPage.current = current;
  loadArchivePurchaseRecordList();
};

// 档案用药提醒数据加载
const loadArchiveMedicationReminder = async () => {
  if (!currentArchiveUser.value) return;

  // 如果是好友，加载用药提醒信息
  if (currentArchiveUser.value.type === '1') {
    try {
      const response = await getMedicationReminderList({
        sendWxId: currentArchiveUser.value.wxAccount,
        wxId: wxId.value
      });
      const res = response as unknown as ApiResponse<{ records: MedicationReminder[]; total: number }>;
      if (res.code === 200 && res.data.records.length > 0) {
        customerMedicationReminder.value = res.data.records[0];
      } else {
        customerMedicationReminder.value = null;
      }
    } catch (error) {
      console.error('获取用药提醒信息失败:', error);
      customerMedicationReminder.value = null;
    }
  } else {
    // 非好友清空用药提醒信息
    customerMedicationReminder.value = null;
  }
};

const handleAddPurchaseRecord = () => {
  purchaseRecordEditMode.value = 'add';
  Object.assign(purchaseRecordForm, {
    id: undefined,
    wxId: currentUserWxId.value,
    myWxId: wxId.value, // 使用当前登录用户的微信ID作为myWxId
    shopName: '',
    orderNo: '',
    receiverName: '',
    receiverPhone: '',
    receiverAddr: '',
    orderDate: undefined,
    productName: '',
    productCode: '',
    productSpec: '',
    quantity: undefined,
    remark: ''
  });
  purchaseRecordEditDialogVisible.value = true;
};

const handleEditPurchaseRecord = (row: PurchaseRecord) => {
  purchaseRecordEditMode.value = 'edit';
  Object.assign(purchaseRecordForm, {
    ...row,
    myWxId: wxId.value, // 确保编辑时也传递当前登录用户的微信ID
    orderDate: row.orderDate ? new Date(row.orderDate) : undefined
  });
  purchaseRecordEditDialogVisible.value = true;
};

const handleDeletePurchaseRecord = async (row: PurchaseRecord) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await deletePurchaseRecord(row.id!);
    const res = response as unknown as ApiResponse<any>;
    if (res.code === 200) {
      ElMessage.success('删除成功');
      await loadPurchaseRecordList();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

const submitPurchaseRecord = async () => {
  if (!purchaseRecordFormRef.value) return;
  await purchaseRecordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        purchaseRecordEditLoading.value = true;
        const formData = {
          ...purchaseRecordForm,
          orderDate: purchaseRecordForm.orderDate ? dayjs(purchaseRecordForm.orderDate).format('YYYY-MM-DD') : undefined
        };

        const response = purchaseRecordEditMode.value === 'add' ? await addPurchaseRecord(formData) : await updatePurchaseRecord(formData);

        const res = response as unknown as ApiResponse<any>;
        if (res.code === 200) {
          ElMessage.success(purchaseRecordEditMode.value === 'add' ? '新增成功' : '编辑成功');
          purchaseRecordEditDialogVisible.value = false;
          await loadPurchaseRecordList();
        } else {
          ElMessage.error(res.msg || '操作失败');
        }
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败');
      } finally {
        purchaseRecordEditLoading.value = false;
      }
    }
  });
};

// 间隔天数处理方法
const handleDayTypeChange = (value: 'daily' | 'custom') => {
  if (value === 'daily') {
    medicationReminderForm.day = 0;
    customDayValue.value = undefined;
  } else {
    medicationReminderForm.day = customDayValue.value;
  }
};

// 计算间隔天数提示内容
const getIntervalDaysTip = (day: number, triple: number) => {
  if (day === 0) {
    // 每天次数提示具体的提示时间
    let times: string[] = [];
    if (triple === 1) {
      times = ['12:00'];
    } else if (triple === 2) {
      times = ['09:00', '15:00'];
    } else if (triple === 3) {
      times = ['08:00', '12:00', '18:00'];
    }
    return `每天${triple}次，提示时间：${times.join('、')}`;
  } else {
    // 自定义间隔天数提示下次提示日期
    const today = new Date();
    const nextDate = new Date(today);
    nextDate.setDate(today.getDate() + day);
    const dateStr = nextDate.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
    return `每${day}天提示一次，下次提示日期：${dateStr}`;
  }
};

const handleCustomDayChange = (value: number) => {
  medicationReminderForm.day = value;
};

// 客服好友选择相关方法
const handleRemoveCustomerServiceFriend = (friend: Friend) => {
  const index = selectedCustomerServiceFriends.value.findIndex((f) => f.wx_id === friend.wx_id);
  if (index > -1) {
    selectedCustomerServiceFriends.value.splice(index, 1);
    medicationReminderForm.customerService = '';
  }
};

const handleCustomerServiceFriendSelectConfirm = (friends: Friend[]) => {
  // 更新选中的客服好友列表
  selectedCustomerServiceFriends.value = friends;

  // 更新表单中的所属客服字段
  if (friends.length > 0) {
    // 如果是多选，用逗号分隔；如果是单选，直接使用第一个
    medicationReminderForm.customerService = friends.map((f) => f.wx_id).join(',');
  } else {
    medicationReminderForm.customerService = '';
  }

  customerServiceFriendSelectDialogVisible.value = false;
};

// 用药提醒相关函数
const handleMedicationReminder = async (row: WechatUser) => {
  currentUserWxId.value = row.wxAccount;
  medicationReminderDialogVisible.value = true;
  await loadMedicationReminder();
};

const loadMedicationReminder = async () => {
  try {
    medicationReminderLoading.value = true;
    const response = await getMedicationReminderList({
      sendWxId: currentUserWxId.value, // 查询时使用客户的微信ID作为接收人ID
      wxId: wxId.value
    });
    const res = response as unknown as ApiResponse<{ records: MedicationReminder[]; total: number }>;
    if (res.code === 200 && res.data.records.length > 0) {
      // 如果有数据，填充表单
      const data = res.data.records[0];
      Object.assign(medicationReminderForm, {
        ...data,
        wxId: wxId.value, // 当前登录用户的微信ID
        sendWxId: currentUserWxId.value // 确保接收人微信ID使用当前用户的wxAccount
      });

      // 处理间隔天数的回显
      if (data.day === 0) {
        dayType.value = 'daily';
        customDayValue.value = undefined;
      } else {
        dayType.value = 'custom';
        customDayValue.value = data.day;
      }

      // 处理客服好友的回显
      if (data.customerServiceList && data.customerServiceList.length > 0) {
        // 使用返回的 customerServiceList 数组来构建好友信息
        selectedCustomerServiceFriends.value = data.customerServiceList.map((service: any) => ({
          wx_id: service.customerService,
          nick_name: service.customerServiceName,
          first_nick_name: service.customerServiceName,
          avatar: '',
          gender: '',
          labels: []
        }));
      } else if (data.customerService) {
        // 兼容旧格式：如果没有 customerServiceList 但有 customerService 字段
        const customerServiceIds = data.customerService.split(',').filter((id: string) => id.trim());
        const customerServiceNames = data.customerServiceName ? data.customerServiceName.split(',') : [];
        selectedCustomerServiceFriends.value = customerServiceIds.map((wxId: string, index: number) => ({
          wx_id: wxId.trim(),
          nick_name: customerServiceNames[index] ? customerServiceNames[index].trim() : wxId.trim(),
          first_nick_name: customerServiceNames[index] ? customerServiceNames[index].trim() : wxId.trim(),
          avatar: '',
          gender: '',
          labels: []
        }));
      } else {
        selectedCustomerServiceFriends.value = [];
      }
    } else {
      // 如果没有数据，初始化表单
      Object.assign(medicationReminderForm, {
        id: undefined,
        wxId: wxId.value, // 当前登录用户的微信ID
        sendWxId: currentUserWxId.value, // 自动设置为当前用户的wxAccount
        day: undefined,
        triple: undefined,
        productName: '',
        message: '',
        status: '1',
        customerService: '',
        customerServiceStatus: '0',
        deadline: ''
      });

      // 重置间隔天数相关变量
      dayType.value = 'daily';
      customDayValue.value = undefined;

      // 重置客服好友选择
      selectedCustomerServiceFriends.value = [];
    }
  } catch (error) {
    console.error('获取用药提醒失败:', error);
    ElMessage.error('获取用药提醒失败');
  } finally {
    medicationReminderLoading.value = false;
  }
};

const submitMedicationReminder = async () => {
  if (!medicationReminderFormRef.value) return;
  await medicationReminderFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        medicationReminderLoading.value = true;
        const response = await updateMedicationReminder(medicationReminderForm);
        const res = response as unknown as ApiResponse<any>;
        if (res.code === 200) {
          ElMessage.success('保存成功');
          medicationReminderDialogVisible.value = false;
        } else {
          ElMessage.error(res.msg || '保存失败');
        }
      } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败');
      } finally {
        medicationReminderLoading.value = false;
      }
    }
  });
};

// 删除客户
const handleDelete = async (row: TableItem) => {
  try {
    await ElMessageBox.confirm(`确定要删除客户 "${row.userName}" 吗？${row.type === '1' ? '删除好友将同时删除微信好友关系。' : ''}`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await deleteWechatUser({
      wechatUser: {
        id: row.customer_id,
        type: row.type,
        wxId: wxId.value,
        sendWxId: row.wxAccount
      }
    });
    const res = response as unknown as ApiResponse<any>;
    if (res.code === 200) {
      ElMessage.success('删除成功');
      handleSearch();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 查看详情
const handleDetail = async (row: TableItem) => {
  detailDialogVisible.value = true;
  customerDetail.value = {
    id: row.customer_id,
    wechatAccountId: row.wxAccount,
    myWxId: '',
    userOpenId: '',
    userWechatUserId: '',
    userName: row.userName,
    userAvatarUrl: row.avatarUrl,
    userEmail: row.userEmail || '-',
    userPhone: row.userPhone || '-',
    userCreateTime: row.createTime,
    userInfoUpdateTime: row.updateTime,
    remark: row.remark || '',
    wxAccount: row.wxAccount,
    userAge: row.userAge && row.userAge !== 0 ? row.userAge : undefined,
    userBirthday: row.userBirthday || '-',
    userQq: row.userQq || '-',
    userAddress: row.userAddress || '-',
    userDescription: row.userDescription || '-',
    userCustomerSource: row.userCustomerSource,
    userAssignedEmployee: row.userAssignedEmployee,
    industry: row.industry || '',
    endMessageTime: row.endMessageTime || '',
    type: row.type,
    labels: row.labels || []
  };

  // 如果是好友，加载用药提醒信息
  if (row.type === '1') {
    try {
      const response = await getMedicationReminderList({
        sendWxId: row.wxAccount,
        wxId: wxId.value
      });
      const res = response as unknown as ApiResponse<{ records: MedicationReminder[]; total: number }>;
      if (res.code === 200 && res.data.records.length > 0) {
        customerMedicationReminder.value = res.data.records[0];
      } else {
        customerMedicationReminder.value = null;
      }
    } catch (error) {
      console.error('获取用药提醒信息失败:', error);
      customerMedicationReminder.value = null;
    }
  } else {
    // 非好友清空用药提醒信息
    customerMedicationReminder.value = null;
  }
};

// 消息处理函数
const processMessageContent = (content: string): string => {
  try {
    return content.replace(/\$\$([^$]+)\]/g, (match: string) => {
      return wechatEmojiMap[match as string] || match;
    });
  } catch (error) {
    console.error('处理提醒内容时出错:', error);
    return content;
  }
};

const processMessageList = (messages: MessageItem[]): MessageItem[] => {
  return messages.map((item) => {
    if (item.message_content) {
      return {
        ...item,
        message_content: processMessageContent(item.message_content)
      };
    }
    return item;
  });
};

// 档案相关处理函数
const handleArchive = (row: TableItem) => {
  currentArchiveUser.value = row;
  activeArchiveTab.value = 'dynamics';
  archiveDialogVisible.value = true;
};

// ChatHistory 组件事件处理
const handleTranscribeAudio = (message: any) => {
  console.log('转录音频:', message);
  // 这里可以添加音频转录的逻辑
};

const handleDownloadFile = (message: any) => {
  console.log('下载文件:', message);
  // 这里可以添加文件下载的逻辑
};

// 处理聊天记录消息请求
const handleChatHistoryMsgSendMessages = async (params: any) => {
  try {
    console.log('请求聊天记录参数:', params);
    const res = await msgSendMessages(params);
    console.log('聊天记录响应:', res);

    const responseData = res.data.records || res.data;
    const processedMessages = processMessageList(responseData.reverse());

    if (chatHistoryRef.value) {
      if (params.current === '1') {
        // 首次加载或查询
        chatHistoryRef.value.chatHistoryMessages = processedMessages;
      } else {
        // 加载更多
        const currentScrollHeight = chatHistoryRef.value.chatHistoryScrollRef?.scrollHeight || 0;
        chatHistoryRef.value.chatHistoryMessages = [...processedMessages, ...chatHistoryRef.value.chatHistoryMessages];

        // 保持滚动位置
        nextTick(() => {
          if (chatHistoryRef.value?.chatHistoryScrollRef) {
            const newScrollHeight = chatHistoryRef.value.chatHistoryScrollRef.scrollHeight;
            chatHistoryRef.value.chatHistoryScrollRef.scrollTop = newScrollHeight - currentScrollHeight;
          }
        });
      }

      chatHistoryRef.value.chatHistoryHasMore = responseData.length === parseInt(chatHistoryRef.value.chatHistorySize);

      // 首次加载完成后滚动到底部
      if (params.current === '1') {
        nextTick(() => {
          chatHistoryRef.value?.scrollChatHistoryToBottom();
        });
      }
    }
  } catch (error) {
    console.error('查询聊天记录失败:', error);
    ElMessage.error('查询聊天记录失败');
    if (chatHistoryRef.value) {
      chatHistoryRef.value.chatHistoryLoadError = true;
    }
  } finally {
    if (chatHistoryRef.value) {
      chatHistoryRef.value.chatHistoryLoading = false;
    }
  }
};

// 客户动态相关函数
const loadCustomerActivities = async (customerWxId: string, isRefresh = false) => {
  if (!customerWxId) return;

  try {
    activitiesLoading.value = true;

    const params = {
      wxId: wxId.value, // 当前登录用户的微信ID
      customerWxId: customerWxId, // 客户的微信ID
      current: activitiesPage.value.current,
      size: activitiesPage.value.size
    };

    const response = await getCustomerLogList(params);
    const records = response.data.records || [];

    // 转换数据格式，与weChat页面保持一致
    const newActivities = records.map((item: any) => ({
      time: item.date_time,
      type: getActivityType(item.log_type),
      color: getActivityColor(item.log_type),
      title: item.log_type_str,
      description: item.remark,
      // 保留原始数据字段以兼容现有代码
      createTime: item.date_time,
      remark: item.remark,
      accountName: item.account_name || '系统'
    }));

    if (isRefresh || activitiesPage.value.current === 1) {
      customerActivities.value = newActivities;
    } else {
      customerActivities.value = [...customerActivities.value, ...newActivities];
    }

    activitiesPage.value.total = response.data.total || 0;
    activitiesPage.value.hasMore = records.length === activitiesPage.value.size;
  } catch (error) {
    console.error('获取客户动态失败:', error);
    ElMessage.error('获取客户动态失败');
  } finally {
    activitiesLoading.value = false;
  }
};

const refreshCustomerActivities = async () => {
  if (!currentArchiveUser.value?.wxAccount) return;

  if (refreshingActivities.value || refreshCountdown.value > 0) {
    ElMessage.warning(`请等待 ${refreshCountdown.value} 秒后再刷新`);
    return;
  }

  refreshingActivities.value = true;
  try {
    activitiesPage.value.current = 1;
    activitiesPage.value.hasMore = true;
    await loadCustomerActivities(currentArchiveUser.value.wxAccount, true);
    startRefreshCountdown();
  } catch (error) {
    console.error('刷新客户动态失败:', error);
    ElMessage.error('刷新客户动态失败');
  } finally {
    refreshingActivities.value = false;
  }
};

const loadMoreActivities = async () => {
  if (!currentArchiveUser.value?.wxAccount || activitiesLoading.value) return;

  activitiesPage.value.current += 1;
  await loadCustomerActivities(currentArchiveUser.value.wxAccount, false);
};

const startRefreshCountdown = () => {
  refreshCountdown.value = 30;
  refreshTimer = setInterval(() => {
    refreshCountdown.value--;
    if (refreshCountdown.value <= 0) {
      clearInterval(refreshTimer!);
      refreshTimer = null;
    }
  }, 1000);
};

const showAddActivityDialog = () => {
  if (!currentArchiveUser.value?.wxAccount) {
    ElMessage.warning('请先选择一个用户');
    return;
  }
  addActivityForm.remark = '';
  addActivityDialogVisible.value = true;
};

// 根据日志类型获取活动类型
const getActivityType = (logType: string) => {
  const typeMap: { [key: string]: string } = {
    '1': 'primary', // 跟进记录
    '2': 'success', // 成交记录
    '3': 'warning', // 投诉记录
    '4': 'danger', // 手动记录
    '5': 'info' // 其他记录
  };
  return typeMap[logType] || 'primary';
};

// 根据日志类型获取活动颜色
const getActivityColor = (logType: string) => {
  const colorMap: { [key: string]: string } = {
    '1': '#2b7bef', // 跟进记录 - 蓝色
    '2': '#44cb84', // 成交记录 - 绿色
    '3': '#e6a23c', // 投诉记录 - 橙色
    '4': '#f56c6c', // 手动记录 - 红色
    '5': '#909399' // 其他记录 - 灰色
  };
  return colorMap[logType] || '#2b7bef';
};

const handleAddActivity = async () => {
  if (!addActivityForm.remark.trim()) {
    ElMessage.warning('请输入动态内容');
    return;
  }

  if (!currentArchiveUser.value?.wxAccount) {
    ElMessage.warning('用户信息异常');
    return;
  }

  try {
    addActivityLoading.value = true;

    const params = {
      logType: 1,
      wxId: wxId.value, // 当前登录用户的微信ID
      customerWxId: currentArchiveUser.value.wxAccount, // 客户的微信ID
      remark: addActivityForm.remark.trim()
    };

    console.log('新增客户动态参数:', params);

    await addCustomerLog(params);
    ElMessage.success('新增动态成功');
    addActivityDialogVisible.value = false;

    // 刷新动态列表
    activitiesPage.value.current = 1;
    activitiesPage.value.hasMore = true;
    await loadCustomerActivities(currentArchiveUser.value.wxAccount, true);
  } catch (error) {
    console.error('新增动态失败:', error);
    ElMessage.error('新增动态失败');
  } finally {
    addActivityLoading.value = false;
  }
};

// 监听档案对话框和选项卡变化，自动加载数据
watch([archiveDialogVisible, activeArchiveTab], ([dialogVisible, activeTab]) => {
  if (dialogVisible && currentArchiveUser.value) {
    if (activeTab === 'chatHistory') {
      // 延迟加载，确保DOM已渲染
      nextTick(() => {
        chatHistoryRef.value?.loadChatHistory();
      });
    } else if (activeTab === 'dynamics') {
      // 加载客户动态
      activitiesPage.value.current = 1;
      activitiesPage.value.hasMore = true;
      customerActivities.value = [];
      loadCustomerActivities(currentArchiveUser.value.wxAccount, true);
    } else if (activeTab === 'purchaseRecord') {
      // 加载购买记录
      archivePurchaseRecordPage.current = 1;
      archivePurchaseRecordList.value = [];
      loadArchivePurchaseRecordList();
    } else if (activeTab === 'medicationReminder') {
      // 加载用药提醒
      loadArchiveMedicationReminder();
    }
  }
});

// 初始化加载数据
handleSearch();
</script>

<style lang="scss" scoped>
.customer-management {
  padding: 20px;
  min-height: calc(100vh - 84px);

  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 8px;
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
          padding: 12px 0;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }

      .tag-list {
        display: flex;
        flex-wrap: wrap;
        gap: 4px;

        .tag-item {
          margin: 0;
        }
      }
    }
  }

  .pagination-section {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
    padding: 12px 0;
  }

  .customer-dialog {
    :deep(.el-dialog__header) {
      padding: 20px;
      margin: 0;
      border-bottom: 1px solid #dcdfe6;
    }

    :deep(.el-dialog__body) {
      padding: 20px;
    }

    .tag-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      align-items: center;

      .tag-item {
        margin: 0;
      }
    }

    .customer-service-list {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;

      .service-tag {
        margin: 0;
      }
    }

    .no-medication {
      text-align: center;
      padding: 20px;
      color: #909399;
    }

    .edit-form {
      max-width: 500px;
      margin: 0 auto;

      .w-full {
        width: 100%;
      }
    }
  }
}
:deep(.el-descriptions__label) {
  width: 120px;
  min-width: 120px;
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  text-align: center;
  vertical-align: middle;
}

:deep(.el-descriptions__content) {
  padding: 12px 16px;
  word-break: break-all;
  white-space: pre-wrap;
  line-height: 1.5;
}

/* 记录对话框样式 */
.purchase-record-dialog {
  .purchase-record-container {
    padding: 20px;
    .operation-section {
      margin: 16px 0;
      display: flex;
      gap: 12px;
    }

    .main-content {
      margin-top: 16px;
    }

    .table-section {
      margin-bottom: 16px;
    }
  }
}

/* 用药提醒对话框样式 */
.medication-reminder-dialog {
  .medication-reminder-container {
    .operation-section {
      margin: 16px 0;
      display: flex;
      gap: 12px;
    }

    .main-content {
      margin-top: 16px;
    }

    .table-section {
      margin-bottom: 16px;
    }
  }
}

/* 对话框内的分页样式 */
:deep(.el-dialog__body) {
  .el-pagination {
    margin-top: 16px;
    display: flex;
    justify-content: center;
  }
}

/* 更多操作菜单样式 */
.more-actions {
  display: flex;
  padding: 8px 0;

  .more-action-btn {
    justify-content: flex-start;
    border-radius: 6px;
    transition: all 0.2s ease;
  }
}

/* 客户信息点击样式 */
.custom-table {
  .el-table__row {
    .customer-info-clickable {
      padding: 4px;
      border-radius: 4px;
      transition: all 0.2s ease;

      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

/* 全局样式，确保对话框样式生效 */
.editDialog.el-dialog {
  margin-top: 5vh !important;
  margin-bottom: 5vh !important;
}

.el-overlay .editDialog {
  margin-top: 5vh !important;
}

.el-dialog__wrapper .editDialog {
  margin-top: 5vh !important;
}

/* 详情页面样式 */
.detail-section {
  margin-bottom: 10px;
  background: #fafbfc;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  padding: 20px;

  .section-title {
    margin: 0 0 20px 0;
    padding: 0 0 10px 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    border-bottom: 2px solid #409eff;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      bottom: -2px;
      width: 30px;
      height: 2px;
      background-color: #409eff;
    }
  }

  .detail-grid {
    padding: 0;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0;

    .detail-item {
      display: flex;
      align-items: flex-start;
      padding: 10px 16px;
      border-bottom: 1px solid #f0f2f5;
      transition: background-color 0.2s;

      &:hover {
        background-color: #fafbfc;
      }

      &.detail-item-full {
        grid-column: 1 / -1;

        .detail-label {
          width: 130px;
        }

        .detail-value {
          margin-left: 12px;
        }
      }

      .detail-label {
        flex-shrink: 0;
        width: 130px;
        color: #606266;
        font-weight: 600;
        font-size: 13px;
        line-height: 1.4;
        background: #f5f7fa;
        padding: 4px 8px;
        border-radius: 3px;
        margin-right: 12px;
        text-align: center;
        border: 1px solid #e4e7ed;
      }

      .detail-value {
        flex: 1;
        color: #303133;
        font-size: 14px;
        line-height: 1.4;
        word-break: break-all;
        padding: 4px 0;
        font-weight: 500;

        &:empty::before {
          content: '-';
          color: #c0c4cc;
          font-style: italic;
        }
      }
    }
  }
}

// 用药提醒对话框样式
.medication-reminder-dialog {
  .medication-reminder-form {
    .form-section {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #fafbfc;
      border-radius: 8px;
      border: 1px solid #e4e7ed;

      .section-title {
        margin: 0 0 20px 0;
        padding: 0 0 10px 0;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        border-bottom: 2px solid #409eff;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          bottom: -2px;
          width: 30px;
          height: 2px;
          background-color: #409eff;
        }
      }

      &:last-child {
        margin-bottom: 0;
      }
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #606266;
      align-items: center;
    }

    :deep(.el-input__wrapper) {
      border-radius: 6px;
    }

    :deep(.el-select) {
      width: 100%;
    }

    :deep(.el-date-editor) {
      width: 100%;
    }

    :deep(.el-input-number) {
      width: 100%;
    }

    :deep(.el-radio-group) {
      display: flex;
      align-items: center;
    }

    :deep(.el-textarea__inner) {
      border-radius: 6px;
    }
  }
}

// 购买记录对话框样式
.purchase-record-dialog {
  .purchase-record-form {
    .form-section {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #fafbfc;
      border-radius: 8px;
      border: 1px solid #e4e7ed;

      .section-title {
        margin: 0 0 20px 0;
        padding: 0 0 10px 0;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        border-bottom: 2px solid #409eff;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          bottom: -2px;
          width: 30px;
          height: 2px;
          background-color: #409eff;
        }
      }

      &:last-child {
        margin-bottom: 0;
      }
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #606266;
    }

    :deep(.el-input__wrapper) {
      border-radius: 6px;
    }

    :deep(.el-select) {
      width: 100%;
    }

    :deep(.el-date-editor) {
      width: 100%;
    }

    :deep(.el-input-number) {
      width: 100%;
    }
  }
}

// 客户编辑对话框样式
.customer-edit-dialog {
  .customer-edit-form {
    .form-section {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #fafbfc;
      border-radius: 8px;
      border: 1px solid #e4e7ed;

      .section-title {
        margin: 0 0 20px 0;
        padding: 0 0 10px 0;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        border-bottom: 2px solid #409eff;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          bottom: -2px;
          width: 30px;
          height: 2px;
          background-color: #409eff;
        }
      }

      &:last-child {
        margin-bottom: 0;
      }
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #606266;
    }

    :deep(.el-input__wrapper) {
      border-radius: 6px;
    }

    :deep(.el-select) {
      width: 100%;
    }

    :deep(.el-date-editor) {
      width: 100%;
    }

    :deep(.el-input-number) {
      width: 100%;
    }

    :deep(.el-textarea__inner) {
      border-radius: 6px;
    }
  }
}

// 标签列表样式优化
.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;

  .tag-item {
    margin: 0;
  }
}

// 无备注样式
.no-remark {
  color: #999;
  font-style: italic;
  font-size: 12px;
}
// .el-col-12 {
//   flex: 0 0 48% !important;
// }
// .el-col-24 {
//   flex: 0 0 96% !important;
// }

/* 档案对话框样式 */
.archive-dialog {
  .archive-content {
    height: 600px;

    .archive-tabs {
      height: 100%;

      :deep(.el-tabs__content) {
        height: calc(100% - 40px);
        overflow: hidden;
      }

      :deep(.el-tab-pane) {
        height: 100%;
        overflow: auto;
      }
    }

    .chat-history-container {
      height: 100%;

      :deep(.mySelfData-myself) {
        height: 100%;

        .mySelfData-myself-center {
          height: 100%;
          display: flex;
          flex-direction: column;

          .section-title {
            margin-bottom: 16px;
          }

          .chat-search-conditions {
            margin-bottom: 16px;
          }

          .chat-history-list {
            flex: 1;
            overflow: auto;
          }
        }
      }
    }

    .personal-info-container {
      height: 100%;
      overflow-y: auto;
      padding: 10px;

      .personal-info-content {
        .info-card {
          background: #fff;
          border: 1px solid #e4e7ed;
          border-radius: 8px;
          margin-bottom: 16px;
          overflow: hidden;

          .card-header {
            background: #f5f7fa;
            padding: 12px 16px;
            border-bottom: 1px solid #e4e7ed;

            .card-title {
              margin: 0;
              font-size: 14px;
              font-weight: 600;
              color: #303133;
            }
          }

          .card-body {
            padding: 16px;

            .info-grid {
              display: grid;
              grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
              gap: 16px;

              .info-item {
                display: flex;
                align-items: center;

                .info-label {
                  width: 80px;
                  font-size: 13px;
                  color: #606266;
                  margin-right: 12px;
                  flex-shrink: 0;
                }

                .info-value {
                  flex: 1;
                  font-size: 13px;
                  color: #303133;
                  word-break: break-all;
                }
              }
            }

            .tags-container {
              display: flex;
              flex-wrap: wrap;
              gap: 8px;

              .tag-item {
                margin: 0;
              }
            }
          }
        }
      }
    }

    .dynamics-container {
      height: 100%;
      overflow-y: auto;
      padding: 10px;

      .dynamics-content {
        .section-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          font-size: 16px;
          font-weight: 600;
          color: #303133;

          .activity-actions {
            display: flex;
            align-items: center;
          }
        }

        .timeline-container {
          padding: 8px;

          .timeline-content {
            .timeline-title {
              font-size: 13px;
              font-weight: 500;
              color: #333;
              margin-bottom: 2px;
              display: flex;
              align-items: center;
              gap: 6px;

              &::before {
                content: '';
                display: inline-block;
                width: 6px;
                height: 6px;
                border-radius: 50%;
                background-color: currentColor;
              }
            }

            .timeline-desc {
              font-size: 12px;
              color: #666;
              line-height: 1.4;
              padding-left: 12px;
            }
          }

          :deep(.el-timeline-item__node) {
            width: 8px;
            height: 8px;
          }

          :deep(.el-timeline-item__timestamp) {
            color: #909399;
            font-size: 12px;
            padding-top: 0;
          }

          :deep(.el-timeline-item__content) {
            padding-left: 12px;
          }

          :deep(.el-timeline-item__tail) {
            left: 3px;
          }

          :deep(.el-timeline-item) {
            padding-bottom: 16px;

            &:last-child {
              padding-bottom: 0;
            }
          }

          .load-more-container {
            text-align: center;
            margin-top: 20px;
            padding: 10px 0;

            .load-more-btn {
              font-size: 14px;
              color: #409eff;

              &:hover {
                color: #66b1ff;
              }
            }

            .no-more-data {
              color: #909399;
              font-size: 12px;
              font-style: italic;
            }
          }

          .empty-activities {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 200px;
            padding: 40px 20px;

            .el-empty {
              .el-empty__image {
                opacity: 0.6;
              }

              .el-empty__description {
                margin-top: 16px;
              }
            }
          }
        }

        // 为不同类型的时间轴项添加不同的颜色
        .timeline-container {
          :deep(.el-timeline-item) {
            &[data-type='success'] {
              .timeline-title {
                color: #44cb84;
              }
            }
            &[data-type='primary'] {
              .timeline-title {
                color: #2b7bef;
              }
            }
            &[data-type='warning'] {
              .timeline-title {
                color: #e6a23c;
              }
            }
            &[data-type='danger'] {
              .timeline-title {
                color: #f56c6c;
              }
            }
          }
        }
      }
    }

    // 用药提醒选项卡样式
    .medication-reminder-container {
      height: 100%;
      overflow-y: auto;
      padding: 10px;

      .medication-reminder-content {
        .info-card {
          background: #fff;
          border: 1px solid #e4e7ed;
          border-radius: 8px;
          margin-bottom: 16px;
          overflow: hidden;

          .card-header {
            background: #f5f7fa;
            padding: 12px 16px;
            border-bottom: 1px solid #e4e7ed;

            .card-title {
              margin: 0;
              font-size: 14px;
              font-weight: 600;
              color: #303133;
            }
          }

          .card-body {
            padding: 16px;

            .info-grid {
              display: grid;
              grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
              gap: 16px;

              .info-item {
                display: flex;
                align-items: center;

                .info-label {
                  width: 80px;
                  font-size: 13px;
                  color: #606266;
                  margin-right: 12px;
                  flex-shrink: 0;
                }

                .info-value {
                  flex: 1;
                  font-size: 13px;
                  color: #303133;
                  word-break: break-all;
                }
              }
            }

            .tags-container {
              display: flex;
              flex-wrap: wrap;
              gap: 8px;

              .tag-item {
                margin: 0;
              }

              .service-tag {
                background-color: #e1f3d8;
                border-color: #b3d8a4;
                color: #529b2e;
              }
            }

            .message-content {
              font-size: 13px;
              color: #303133;
              line-height: 1.6;
              padding: 12px;
              background: #f8f9fa;
              border-radius: 6px;
              border-left: 4px solid #409eff;
              white-space: pre-wrap;
              word-break: break-word;
            }
          }
        }

        .empty-medication-reminder {
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 300px;
          padding: 40px 20px;

          .el-empty {
            .el-empty__image {
              opacity: 0.6;
            }

            .el-empty__description {
              margin-top: 16px;
            }
          }
        }
      }
    }

    // 购买记录选项卡样式
    .purchase-record-tab-container {
      height: 100%;
      display: flex;
      flex-direction: column;
      padding: 16px;

      .purchase-record-filter {
        margin-bottom: 16px;
        background: #f8f9fa;
        padding: 16px;
        border-radius: 8px;
        border: 1px solid #e9ecef;
      }

      .purchase-record-table-section {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .custom-table {
          flex: 1;
          margin-bottom: 16px;

          :deep(.el-table__header) {
            background-color: #f5f7fa;

            th {
              background-color: #f5f7fa !important;
              color: #606266;
              font-weight: 600;
              font-size: 13px;
              border-bottom: 1px solid #e4e7ed;
            }
          }

          :deep(.el-table__row) {
            &:hover {
              background-color: #f5f7fa;
            }

            td {
              padding: 12px 0;
              font-size: 13px;
              color: #606266;
              border-bottom: 1px solid #ebeef5;
            }
          }
        }

        .pagination-container {
          display: flex;
          justify-content: flex-end;
          padding: 16px 0;
          border-top: 1px solid #e4e7ed;
          background: #fafafa;
          margin-top: auto;

          :deep(.el-pagination) {
            .btn-prev,
            .btn-next,
            .el-pager li {
              background-color: #fff;
              border: 1px solid #dcdfe6;
              color: #606266;

              &:hover {
                color: #409eff;
                border-color: #409eff;
              }

              &.active {
                background-color: #409eff;
                border-color: #409eff;
                color: #fff;
              }
            }
          }
        }
      }
    }
  }
}
// 提示图标样式
.info-tip-icon,
.form-tip-icon {
  font-size: 14px;
  color: #909399;
  cursor: help;
  margin-left: 4px;

  &:hover {
    color: #409eff;
  }
}

.info-label {
  display: flex;
  align-items: center;
}
</style>
